package com.netbao.realm;

//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.toolkit.StringUtils;
//import com.kn.sys.entity.User;
//import com.kn.sys.mapper.EnterpriseMapper;
//import com.kn.sys.mapper.UserMapper;
//import com.kn.util.ConstUtil;
//import com.kn.util.ShiroUtils;
import com.netbao.model.StatusCode;
import com.netbao.sys.mapper.EnterpriseMapper;
import com.netbao.sys.mapper.UserMapper;
import com.netbao.sys.model.Role;
import com.netbao.sys.model.User;
import com.netbao.sys.model.UserExample;
import com.netbao.sys.service.RoleService;
import com.netbao.sys.service.UserService;
import com.netbao.sys.utils.ShiroUtils;
import com.netbao.sys.vomapper.RoleUserVoMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author Li Ruihuan
 * @create 2019-06-30 10:38
 */
@Component
public class UserRealm extends AuthorizingRealm {
    @Resource
    private RoleService roleService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserService userService;
    @Resource
    private RoleUserVoMapper roleUserVoMapper;
    @Resource
    private EnterpriseMapper enterpriseMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user= (User) principals.getPrimaryPrincipal();//获取身份
        Integer userid = user.getId();
        List<String> permsList=roleUserVoMapper.getperms(userid);// userMapper.queryAllPerms( userid );
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isEmpty( perms )){
                continue;
            }
            permsSet.addAll( Arrays.asList(perms.trim().split(",")));
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }


    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
        shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
        shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
        super.setCredentialsMatcher(shaCredentialsMatcher);
    }
    //登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String account=((UsernamePasswordToken) token).getUsername();
        UserExample example=new UserExample();
        example.createCriteria().andAccountEqualTo(account);
        User user = userMapper.selectByExample(example).get(0);
        if(user==null){
            throw new UnknownAccountException("账号或密码不正确");
        }
        //重复登录
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        DefaultWebSessionManager sessionManager = (DefaultWebSessionManager)securityManager.getSessionManager();
        Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();//获取当前已登录的用户session列表
        for(Session session:sessions){
            //清除该用户以前登录时保存的session
            User u=null;
            try {
                u= (User) session.getAttribute(StatusCode.SESSIONUSER);
            }catch (Exception e){
                continue;
            }
            if(u==null|| StringUtils.isEmpty( u.getAccount( ))){
                continue;
            }
            if(account.equalsIgnoreCase(u.getAccount())) {
                sessionManager.getSessionDAO().delete(session);
            }
        }
        ShiroUtils.setSessionAttribute( StatusCode.SESSIONUSER,user );
        ShiroUtils.setSessionAttribute( StatusCode.SESSIONENTEPRISE,enterpriseMapper.selectByPrimaryKey((long)user.getEid()) );
        List<Role> roleList=roleService.findByUserId((long) user.getId().intValue());
        ShiroUtils.setSessionAttribute("roleList",roleList);
        return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getAccount()), getName());
    }
}
